package com.violet.utils;

import com.violet.properties.ExecutorProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class ExecutorUtils {

    private final ExecutorProperties properties;
    private volatile ThreadPoolExecutor executor;

    // 线程池
    public ThreadPoolExecutor getExecutor() {
        if (executor != null) return executor;

        synchronized (this) {
            if (executor == null) {
                executor = new ThreadPoolExecutor(
                        properties.getCoreSize(),                                       // 核心线程数，处理持续的任务负载
                        properties.getMaxSize(),                                        // 最大线程数，处理任务高峰
                        properties.getKeepAliveTime(),                                  // 线程空闲时间，超过此时间线程会被回收
                        TimeUnit.SECONDS,                                               // 时间单位
                        new LinkedBlockingDeque<>(properties.getQueueCapacity()),       // 任务队列
                        Executors.defaultThreadFactory(),                               // 线程工厂
                        new ThreadPoolExecutor.AbortPolicy()                            // 拒绝策略
                );
            }
            return executor;
        }
    }
}
